class Carousel {
  /**
   *
   * @param {*} props
   * @param {string} props.id
   * @param {any[]} props.images
   */
  constructor(props) {
    this.images = props.images;
    this.ele = document.getElementById(props.id);

    this.index = 0;
    // 执行初始化
    this.init();
  }

  // 初始化
  init() {
    const length = this.images.length;
    this.createElement(length);
  }

  // 创建dom
  createElement(length) {
    let html = ``;
    for (let i = 0; i < length; i++) {
      html += `<li style='background:${this.images[i].background}'>${this.images[i].text}</li>`;
    }

    html += `<li style='background:${this.images[0].background}'>${this.images[0].text}</li>`;
    this.ele.innerHTML = `<ul>${html}</ul>`;

    this.scroll();
  }

  // 执行滚动
  scroll() {
    const ulEle = this.ele.getElementsByTagName("ul");
    setInterval(() => {
      // 这里设置变速
      if (ulEle[0].style["transition-duration"] === "0s") {
        ulEle[0].style["transition-duration"] = "1s";
      }
      if (this.index < this.images.length) {
        this.index += 1;
        ulEle[0].style.left = `-${200 * this.index}px`;

        if (this.index === this.images.length) {
          setTimeout(() => {
            ulEle[0].style["transition-duration"] = "0s";
            this.index = 0;
            ulEle[0].style.left = 0;
          }, 1000);
        }
      }
      console.log(ulEle[0].style.left);
    }, 3000);
  }
}

const objCarousel = new Carousel({
  id: "carousel",
  images: [
    { text: 122, background: "red" },
    { text: 222, background: "grey" },
    { text: 322, background: "blue" },
    { text: 422, background: "green" },
    { text: 522, background: "white" },
  ],
});
